import android.app.Activity
import android.widget.Toast
import androidx.activity.compose.BackHandler
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideIn
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOut
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationBarItemDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.ramcosta.composedestinations.DestinationsNavHost
import com.ramcosta.composedestinations.animations.defaults.DestinationEnterTransition
import com.ramcosta.composedestinations.animations.defaults.DestinationExitTransition
import com.ramcosta.composedestinations.animations.defaults.NavGraphDefaultAnimationParams
import com.ramcosta.composedestinations.animations.defaults.RootNavGraphDefaultAnimations
import com.ramcosta.composedestinations.rememberNavHostEngine
import kotlinx.coroutines.launch
import org.hank.compose_yyzs.R
import org.hank.compose_yyzs.ui.NavGraphs
import org.hank.compose_yyzs.ui.appCurrentDestinationAsState
import org.hank.compose_yyzs.ui.destinations.Destination
import org.hank.compose_yyzs.ui.destinations.MeasureResultScreenDestination
import org.hank.compose_yyzs.ui.destinations.ProjectScreenDestination
import org.hank.compose_yyzs.ui.destinations.ScanScreenDestination
import org.hank.compose_yyzs.ui.destinations.SettingScreenDestination
import org.hank.compose_yyzs.ui.destinations.TipsDialogDestination
import org.hank.compose_yyzs.ui.startAppDestination
import org.hank.compose_yyzs.ui.theme.AppTheme

@Composable
fun MyNaviHost() {
    var engine = rememberNavHostEngine(rootDefaultAnimations = MyNavDefaultAnimationParams.ACCOMPANIST_FADE)
    var navController = engine.rememberNavController()
    val destination = navController.appCurrentDestinationAsState().value
        ?: NavGraphs.root.startRoute.startAppDestination
    Scaffold(bottomBar = {
        if (destination.shouldShowScaffoldElements ||
            destination.isLastMainDestination(navController)
        ) {
            MyBottomBar(navController)
        }
    }) {
        DestinationsNavHost(
            engine = engine,
            navController = navController,
            navGraph = NavGraphs.root,
            startRoute = NavGraphs.root.startRoute,
            modifier = Modifier.padding(it),
        )
    }
}

private fun Destination.isLastMainDestination(navController: NavController): Boolean {
    if (this is TipsDialogDestination) {
        if (navController.previousBackStackEntry?.destination?.route == ProjectScreenDestination.route ||
            navController.previousBackStackEntry?.destination?.route == ScanScreenDestination.route ||
            navController.previousBackStackEntry?.destination?.route == MeasureResultScreenDestination.route ||
            navController.previousBackStackEntry?.destination?.route == SettingScreenDestination.route
        )
            return true
    }
    return false
}

private val Destination.shouldShowScaffoldElements
    get() = this is ProjectScreenDestination ||
            this is ScanScreenDestination ||
            this is MeasureResultScreenDestination ||
            this is SettingScreenDestination

class MyNavDefaultAnimationParams(
    override val enterTransition: DestinationEnterTransition = DestinationEnterTransition { EnterTransition.None },
    override val exitTransition: DestinationExitTransition = DestinationExitTransition { ExitTransition.None },
    override val popEnterTransition: DestinationEnterTransition = enterTransition,
    override val popExitTransition: DestinationExitTransition = exitTransition,
) : NavGraphDefaultAnimationParams {
    companion object {
        val ACCOMPANIST_FADE by lazy {
            RootNavGraphDefaultAnimations(
                enterTransition = {
                    fadeIn(
                        animationSpec = tween(400),
                        initialAlpha = 0f)
                },
                exitTransition = {
                    fadeOut(
                        animationSpec = tween(400),
                        targetAlpha = 0f)
                }
            )
        }
    }
}

@Composable
fun MyBottomBar(navController: NavController) {
    var items = listOf(
        ProjectScreenDestination,
        ScanScreenDestination,
        MeasureResultScreenDestination,
        SettingScreenDestination,
    )
    var selecItem by remember { mutableStateOf(0) }
    Surface(shadowElevation = 8.dp) {
        NavigationBar(
            containerColor = AppTheme.colors.mainColor,
        ) {
            items.forEachIndexed { index, screen ->
                NavigationBarItem(
                    colors = NavigationBarItemDefaults.colors(
                        indicatorColor = MaterialTheme.colorScheme.onSecondary
                    ),
                    selected = selecItem == index, onClick = {
                        selecItem = index
                        navController.navigate(
                            when (index) {
                                0 -> ProjectScreenDestination.route
                                1 -> ScanScreenDestination.route
                                2 -> MeasureResultScreenDestination.route
                                3 -> SettingScreenDestination.route
                                else -> ProjectScreenDestination.route
                            }
                        ) {
                            launchSingleTop = true
                            restoreState = true
                            popUpTo(navController.graph.startDestinationId) {
                                saveState = true
                            }
                        }
                    },
                    icon = {
                        Icon(
                            painter = painterResource(
                                id = when (index) {
                                    0 -> if (selecItem == index) R.mipmap.tabbar_home_pressed else R.mipmap.tabbar_home_normal
                                    1 -> if (selecItem == index) R.mipmap.tabbar_scan_pressed else R.mipmap.tab_scan_normal
                                    2 -> if (selecItem == index) R.mipmap.tabbar_result_pressed else R.mipmap.ic_menu_result
                                    3 -> if (selecItem == index) R.mipmap.tabbar_set_pressed else R.mipmap.tabbar_set_normal
                                    else -> R.mipmap.ic_menu_home
                                }
                            ),
                            contentDescription = "",
                            tint = Color.Black
                        )
                    }, label = {
                        Text(
                            modifier = Modifier.padding(top = 4.dp),
                            text = stringResource(
                                id =
                                when (index) {
                                    0 -> R.string.main_menu_home
                                    1 -> R.string.main_menu_scan
                                    2 -> R.string.main_menu_measure
                                    3 -> R.string.main_menu_setting
                                    else -> R.string.main_menu_setting
                                }
                            ),
                            style = MaterialTheme.typography.bodyMedium.copy(fontWeight = if (selecItem == index) FontWeight.Bold else null),
                            maxLines = 1,
                            overflow = TextOverflow.Ellipsis
                        )
                    })
            }
        }
    }
}

@Composable
fun DoubleClickQuitCompose(content: @Composable (() -> Unit)) {
    var clickTime by remember { mutableStateOf(0L) }
    val context = LocalContext.current
    val scope = rememberCoroutineScope()

    Surface(modifier = Modifier.fillMaxSize()) {
        content()
    }

    BackHandler(true) {
        scope.launch {
            if (clickTime == 0L) {
                Toast.makeText(context, "click again close", Toast.LENGTH_SHORT).show()
                clickTime = System.currentTimeMillis()
            } else
                if ((System.currentTimeMillis() - clickTime) < 1000) {
                    (context as Activity).finish()
                } else {
                    clickTime = 0
                }
        }
    }
}